<template>
  <div class="wrap-list">
    <!--搜索栏 start-->
    <el-row>
      <el-col :span="24" class="handle">
        <el-form ref="form" :model="taskPage" size="mini" :inline="true">
          <el-row>
            <el-col :span="24">
              <el-form-item label="调度名称">
                <el-input v-model="taskPage.invokeName" placeholder="请输入" style="width:200px;"></el-input>
              </el-form-item>
              <el-form-item label="执行状态">
                <el-select v-model="taskPage.status" placeholder="全部" style="width:200px;margin-right: 10px;">
                  <el-option label="全部" value="4"></el-option>
                  <el-option label="待执行" value="0"></el-option>
                  <el-option label="执行中" value="1"></el-option>
                  <el-option label="执行成功" value="2"></el-option>
                  <el-option label="执行失败" value="3"></el-option>
                </el-select>
                <el-button icon="el-icon-search" type="primary" @click="onloadTaskList">查询</el-button>
                <el-button icon="el-icon-refresh" @click="onclickReset">重置</el-button>
                <el-button icon="el-icon-circle-plus-outline" type="success" @click="onclickAddBox" >添加</el-button>
                <el-button icon="el-icon-delete" type="danger" @click="onclickDelete">批量删除</el-button>
                <el-button icon="el-icon-caret-right" type="success" @click="ImmExecution" >立即执行</el-button>
                <!--<el-button icon="el-icon-refresh" type="success" @click="refresh" >刷新</el-button>-->
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <!--搜索栏 end-->

    <el-table
      class="table-height"
      ref="multipleTable"
      v-loading="isLoading"
      :data="dataList"
      tooltip-effect="dark"
      @row-click="onclickShowList"
      @select = "selAll"
      @select-all = "selAll"
      @selection-change="handleSelectionChange">
      <el-table-column :reserve-selection="true" align="center" type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="invokeName" width="180" label="调度任务名称" show-overflow-tooltip></el-table-column>
      <el-table-column label="调度执行状态" width="220">
        <template slot-scope="scope">
          <div v-if="scope.row.lastSatus==0">
            <el-progress :percentage="scope.row.stateSpeed"></el-progress>
          </div>
          <div v-if="scope.row.lastSatus==1">
            <el-progress :percentage="scope.row.stateSpeed"></el-progress>
          </div>
          <el-tooltip class="item" effect="dark" :content="scope.row.lastTaskSuccessTotal+'/'+scope.row.lastTaskTotal" placement="top-start">
            <div v-if="scope.row.lastSatus==2">
              <el-progress :percentage="scope.row.stateSpeed" status="success"></el-progress>
            </div>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" :content="scope.row.lastTaskSuccessTotal+'/'+scope.row.lastTaskTotal" placement="top-start">
            <div v-if="scope.row.lastSatus==3">
              <el-progress :percentage="scope.row.stateSpeed" status="exception"></el-progress>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="调用时间" width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.lastStartTime">{{scope.row.lastStartTime | formatDate}}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column prop="total" label="执行次数" show-overflow-tooltip></el-table-column>
      <el-table-column prop="tag" label="标签" show-overflow-tooltip></el-table-column>
      <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
      <el-table-column width="200" label="操作" show-overflow-tooltip>
        <template slot-scope="scope" >
          <el-button class="xq" @click.stop="updateOrDetail(scope.row, true)" type="text" size="small">
            <el-tooltip class="item" effect="dark" content="调度详情" placement="bottom"><i class="el-icon-view"></i></el-tooltip>
          </el-button>
          <el-button class="xq" @click.stop="showTaskDetail(scope.row)" type="text" size="small">
            <el-tooltip class="item" effect="dark" content="历史详情" placement="bottom"><i class="el-icon-document"></i></el-tooltip>
          </el-button>
          <el-button  class="xg" @click.stop="updateOrDetail(scope.row)" :disabled="scope.row.status === 1" type="text" size="small">
            <el-tooltip class="item" effect="dark"  content="修改" placement="bottom"><i class="el-icon-edit"></i></el-tooltip>
          </el-button>
          <el-button v-if="scope.row.status === 0 || scope.row.status === 2" class="xg" @click.stop="settingEnable(scope.row)" type="text" size="small">
            <el-tooltip class="item" effect="dark"  content="开始" placement="bottom"><i class="el-icon-caret-right"></i></el-tooltip>
          </el-button>
          <el-button v-else class="xg" @click.stop="settingEnable(scope.row)" type="text" size="small">
            <el-tooltip class="item" effect="dark"  content="暂停" placement="bottom"><span>| |</span></el-tooltip>
          </el-button>
          <el-button  class="xq" @click.stop="taskDelete(scope.row)" type="text" size="small">
            <el-tooltip class="item" effect="dark" content="删除" placement="bottom"><i class="el-icon-delete"></i></el-tooltip>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="taskPage.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="taskPage.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="taskPage.total">
      </el-pagination>
    </div>

    <!--立即执行弹框-->
    <el-dialog  :visible.sync="immDialog" width="30%">
      <el-form :model="form" :rules="rules" ref="form" class="concurrentCSS">
        <el-form-item label="并发数" label-width="80px" prop="number">
          <el-input v-model="form.number" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="startExecution('form')" size="small">确 定</el-button>
      </div>
    </el-dialog>

    <!--调度详情-->
    <task-dispatch-detail v-if="isTaskDetails" :dialog="isTaskDetails" :taskInvokeId="taskInvokeId" @closeTaskDispatchDetailCall="closeTaskDispatchDetailCall"/>
  </div>
</template>
<script>
  import { formatDateTime } from "@/libs/utils"
  import addOrUpdateDispatch from './AddOrUpdateDispatch'
  import TaskDispatchDetail from './TaskDispatchDetail'
  export default{
    components: { addOrUpdateDispatch, TaskDispatchDetail },
    data(){
      return {
        isTaskDetails: false,
        dataList: [],
        isLoading: true,
        taskPage: {
          pageNum: 1,
          pageSize: 10,
          total: 0,
          invokeName: '',
          status: '',
          startTime: '',
          invokeCycle: '',
        },
        interval: null,
        disabled: false,
        multipleSelection: [],
        form: {
          number:"",
        },
        immDialog:false,
        selArr:[],
        rules: {
          number: [
            { required: true, message: '请填写并发数', trigger: 'blur' }
          ]
        },
        type: 0,
      }
    },
    created(){
      this.onloadTaskList()
      this.interval = setInterval(() => {
        this.onloadTask();
      }, 2000);
    },
    mounted() {

    },
    beforeDestroy() {
      clearInterval(this.interval);
    },
    methods:{
      closeTaskDispatchDetailCall() {
        this.isTaskDetails = false;
      },
      /**分页Key值**/
      getRowKeys(row) {
        return row.taskId;
      },
      /**点击添加按钮**/
      onclickAddBox() {
        this.$router.push({
          name: "addDispatching",
          params: {
            detail :{},
            disabled : false,
            type : 0,
          }
        })
      },
      /*自动刷新*/
      onloadTask(){
        this.$http.get('/taskInvoke/taskInvokePages', {
          params: {
            pageSize: this.taskPage.pageSize,
            pageNum: this.taskPage.pageNum,
            invokeName: this.taskPage.invokeName,
            status: this.taskPage.status,
          }
        }).then((res) => {
          let resData = res.list;
          for (let i = 0; i < resData.length; i++) {
            let num = resData[i].lastTaskSuccessTotal / resData[i].lastTaskTotal
            if (isNaN(num)) {
              num = 0
            }
            resData[i].stateSpeed = Math.ceil(num * 100)
            if (resData[i].status == 0) {
              resData[i].display = false
            } else {
              resData[i].display = true
            }
            resData[i].tasks.forEach((item, index) => {
              let n = resData[i].tasks[index].interfaceSuccessTotal / resData[i].tasks[index].interfaceTotal
              if (isNaN(n)) {
                n = 0
              }
              resData[i].tasks[index].percentage = Math.ceil(n * 100)
            })
          }
          for(let i = 0;i < resData.length; i++){
            this.dataList[i].lastSatus = resData[i].lastSatus;
            this.dataList[i].stateSpeed = resData[i].stateSpeed;
            this.dataList[i].lastTaskSuccessTotal = resData[i].lastTaskSuccessTotal;
            this.dataList[i].lastTaskTotal = resData[i].lastTaskTotal;
            this.dataList[i].lastStartTime = resData[i].lastStartTime;
            this.dataList[i].total = resData[i].total;
            this.dataList[i].tag = resData[i].tag;
          }
        })
      },
      /**初始化加载列表**/
      onloadTaskList(){
        let url='?pageSize='+this.taskPage.pageSize+'&pageNum='+this.taskPage.pageNum
        if(this.taskPage.invokeName!=''){
          url+='&invokeName='+this.taskPage.invokeName
        }
        if(this.taskPage.status!=''){
          url+='&status='+this.taskPage.status
        }
        this.$http.get('/taskInvoke/taskInvokePages'+url)
          .then((res)=>{
            this.loading=false
            let resData = res.list
            this.taskPage.total=res.total;
            for(let i=0;i<resData.length;i++){
              // let item ={}
              let num = resData[i].lastTaskSuccessTotal/resData[i].lastTaskTotal
              if(isNaN(num)){
                num=0
              }
              resData[i].stateSpeed = Math.ceil(num*100)
              if(resData[i].status==0){
                resData[i].display = false
              }else{
                resData[i].display = true
              }
              resData[i].tasks.forEach((item,index)=>{
                let n = resData[i].tasks[index].interfaceSuccessTotal/resData[i].tasks[index].interfaceTotal
                if(isNaN(n)){
                  n=0
                }
                resData[i].tasks[index].percentage=Math.ceil(n*100)
              })
            }
            this.dataList = resData;
            setTimeout(() => {
              this.isLoading = false;
            }, 500);
          }).catch(() => {
          setTimeout(() => {
            this.isLoading = false;
          }, 500);
        })
      },
      /**设置启用或禁用**/
      settingEnable(data){
        console.log(data);
        this.$http.post('/taskInvoke/batchUpdateStatus',[{
          status: data.status,
          taskInvokeId: data.taskInvokeId
        }]).then((res)=>{
            this.onloadTaskList();
          }).catch((err)=>{

        })
      },
      /**点击重置**/
      onclickReset() {
        this.taskPage = {
          pageNum: 1,
          pageSize: 10,
          total: 0,
          invokeName: '',
          status: '',
          startTime: '',
          invokeCycle: '',
        }
        this.onloadTaskList()
      },
      /**删除单个调度**/
      taskDelete(data){
        this.multipleSelection=[];
        this.multipleSelection.push(data);
        this.onclickDelete();
      },
      /**点击删除**/
      onclickDelete(){
        if(this.multipleSelection.length>0){
          this.$confirm('此操作将永久删除数据, 是否删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let taskInvokeId =[];
            for(let i=0;i<this.multipleSelection.length;i++){
              taskInvokeId.push(this.multipleSelection[i].taskInvokeId)
            }
            this.$http.post('/taskInvoke/deleteInvoke',taskInvokeId)
              .then((res)=>{
                let tData = this.dataList
                for(let j=0;j<taskInvokeId.length;j++){
                  for(let k=0;k<tData.length;k++){
                    if(tData[k].taskInvokeId==taskInvokeId[j]){
                      this.dataList.splice(k,1)
                    }
                  }
                }
                this.$message({message: '删除成功',type: 'success'});
                this.$refs.multipleTable.clearSelection();
              })
          }).catch(() => {});
        }else{
          this.$message({ message: '请选择删除项', type: 'warning' });
        }
      },
      /**点击列表行**/
      onclickShowList(row){
        console.log(row)
      },
      selAll(selection){
        this.selArr=[];
        selection.forEach((item)=>{
          this.selArr.push(item.taskInvokeId)
        })
      },
      /**立即执行**/
      ImmExecution(){
        this.form.number="";
        console.log(this.selArr);
        if (this.selArr.length>0){
          //this.immDialog=true;
          this.$http.post("/taskInvoke/start",
            this.selArr
          )
            .then((rsp)=> {
              this.$message({ type: 'success', message: '执行成功!'});
            })
        }else{
          this.$message.error('请至少勾选一个集成测试！');
        }
      },
      startExecution(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.immDialog=false;
            this.$http.put("/taskInvoke/start/"+this.form.number,this.selArr)
              .then((rsp)=> {
                this.$message({ type: 'success', message: '执行成功!' });
              })
          } else {
            return false;
          }
        });
      },
      /**设置详情**/
      updateOrDetail(data, type) {
        this.$http.get(`/taskInvoke/getInvokeDetail/${data.taskInvokeId}`).then(res => {
          if (type) {
            this.disabled = true;
            this.type = 2;
          }
          else {
            this.disabled = false;
            this.type = 1;
          }
          this.$router.push({
            name: "addDispatching",
            params: {
              detail : res,
              disabled : this.disabled,
              type : this.type,
            }
          })
        });
      },
      /**详情调度任务状态   0，代表待执行 1，代表执行中  2，执行成功，3，执行失败**/
      showTaskDetail(data) {
        this.taskInvokeId = data.taskInvokeId
        this.isTaskDetails = false
        this.$nextTick(() => {
          this.isTaskDetails = true
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleSizeChange(val) {
        this.taskPage.pageSize = val;
        this.onloadTaskList()
      },
      handleCurrentChange(val) {
        this.taskPage.pageNum = val;
        this.onloadTaskList()
      },
      /**刷新**/
      refresh () {
        this.isLoading = true;
        this.taskPage.pageNum = 1;
        this.onloadTaskList();
      },
    },
    filters: {
      formatDate(time) {
        let date = new Date(time);
        return formatDateTime(date, 'yyyy-MM-dd hh:mm:ss');
      }
    }
  }
</script>

<style scoped lang="less">
  .wrap-list{
    height: 100%;
    position: relative;
    .handle{
      /*border-bottom: 10px solid #e2eaed;*/
    }
    .table-height{
      height: calc(100% - 47px - 47px);
    }
    .pager{
      position: absolute;
      width: 100%;
      bottom: 0;
    }
  }
</style>
